package app;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.example.menhoo.toollibrary.android.log.Log;
import com.example.menhoo.toollibrary.common.assist.Check;
import com.example.menhoo.toollibrary.common.helper.MessageUtil;
import com.example.menhoo.toollibrary.common.helper.PhoneUtil;
import com.example.menhoo.toollibrary.common.utils.BitmapUtil;
import com.example.menhoo.toollibrary.common.utils.HandlerUtil;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.callback.BitmapLoadCallBack;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.util.LogUtils;
import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import app.im.IMDetails2;
import app.im.details.IMDetailsActivity;
import application.AppApplication;
import application.HttpUrlConstant;
import custom.ScaleImagesActivity;
import interfaces.IReturnObject;
import mainUI.AppActivity;
import menhoo.com.i8officelibrary.R;
import model.IMCvnDBModel;
import model.ImageInfo;
import utils.Utils;

/**
 * 联系人详情
 * Created by yanglei on 15/10/7.
 */

public class ContactInfo extends AppActivity {


    ImageView imageViewUser;

    TextView textViewName;

    TextView textViewDeptAndPos;

    LinearLayout linearLayoutPhoneAndEmailInfo;

    LinearLayout linearLayoutOtherInfo;

    Button buttonSendImMsg;

    String phone_info = null;
    String email_info = null;
    String mobile_info = null;
    HashMap<String, String> other_info_map = new HashMap();

    String emplID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            emplID = getIntent().getExtras().getString("emplID");
        } catch (Exception ex) {
            emplID = null;
            MessageUtil.showShortToast(this, "emplID is null");
            onBackPressed();
        }
        //
        setContentView(R.layout.contact_info);
        try {
            imageViewUser = (ImageView) findViewById(R.id.imageViewUser);
            textViewName = (TextView) findViewById(R.id.textViewName);
            textViewDeptAndPos = (TextView) findViewById(R.id.textViewDeptAndPos);
            linearLayoutPhoneAndEmailInfo = (LinearLayout) findViewById(R.id.linearLayoutPhoneAndEmailInfo);
            linearLayoutOtherInfo = (LinearLayout) findViewById(R.id.linearLayoutOtherInfo);
            buttonSendImMsg = (Button) findViewById(R.id.buttonSendImMsg);

            if (AppApplication.getUser().EmplID.equalsIgnoreCase(emplID)) {
                buttonSendImMsg.setVisibility(View.GONE);
            }


            buttonSendImMsg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    HandlerUtil.runOnUiThreadDelay(new Runnable() {
                        @Override
                        public void run() {
                            requestDataById(emplID, "couple", new IReturnObject<IMCvnDBModel>() {
                                @Override
                                public void returnResult(IMCvnDBModel result) {
                                    System.out.println(result);
                                    try {
                                        getDB().save(result);
                                    } catch (Exception ex) {
                                        LogUtils.e(ex.getMessage() + "");
                                    }

                                    //
                                    try {
                                        IMCvnDBModel item = result;
                                        item.unreadCount = 0;
                                        getDB().update(item);

                                        Intent it = new Intent(ContactInfo.this, IMDetailsActivity.class);
                                        it.putExtra("Title", item.name);
                                        it.putExtra("UnreadCount", item.unreadCount);
                                        it.putExtra("UserCount", item.userCount);
                                        it.putExtra("GroupID", item.groupID);
                                        it.putExtra("Type", item.type);
                                        it.putExtra("ID", item.id);
                                        startActivity(it);
                                        //
                                        onBackPressed();
                                    } catch (Exception ex) {
                                    }
                                }
                            });
                        }
                    }, 50);
                }
            });
        } catch (Exception e) {
            LogUtils.e(e.getMessage() + "");
        }


        setTitle("详细信息");

        hideContent();
        requestEmplInfo();
    }

    /**
     * 请求人员的详细信息
     */
    private void requestEmplInfo() {
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("empid", emplID);
        Post(HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.GetempInfo), params, new IReturnObject<String>() {
            @Override
            public void returnResult(String result) {
                if (result != null) {
                    System.out.println(result);
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject.getBoolean("Succeed")) {
                            final String EmpName = jsonObject.getString("EmpName");
                            String Dept = jsonObject.getString("Dept");

                            JSONObject dataChild = jsonObject.getJSONObject("Data");
                            if (dataChild.length() > 0) {
                                for (Iterator itr = dataChild.keys(); itr.hasNext(); ) {
                                    String key = (String) itr.next();
                                    if (key.equalsIgnoreCase("手机")) {
                                        mobile_info = dataChild.getString(key);
                                        continue;
                                    } else if (key.equalsIgnoreCase("电话")) {
                                        phone_info = dataChild.getString(key);
                                        continue;
                                    } else if (key.equalsIgnoreCase("电子邮件")) {
                                        email_info = dataChild.getString(key);
                                        continue;
                                    } else {
                                        other_info_map.put(key, dataChild.getString(key));
                                    }

                                }

                            }


                            Map<String, String> parm = new HashMap<String, String>();
                            parm.put("emplid", emplID);
                            final String imgUrl = HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant
                                    .doShowPhoto, parm);

                            textViewName.setText(EmpName);
                            textViewDeptAndPos.setText(Dept);

                            getBitmapLoader().display(imageViewUser, imgUrl, new BitmapLoadCallBack<ImageView>() {
                                @Override
                                public void onLoadCompleted(ImageView imageView, String s, Bitmap bitmap, BitmapDisplayConfig bitmapDisplayConfig,
                                                            BitmapLoadFrom bitmapLoadFrom) {
                                    imageView.setImageBitmap(BitmapUtil.getRoundedCornerBitmap(bitmap, 15f));
                                }

                                @Override
                                public void onLoadFailed(ImageView imageView, String s, Drawable drawable) {
                                    imageView.setImageResource(R.mipmap.untitled);
                                }
                            });

                            imageViewUser.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent it = new Intent(ContactInfo.this, ScaleImagesActivity.class);// 创建Intent对象
                                    it.putExtra("imageInfo", new ImageInfo(EmpName, imgUrl));
                                    startActivity(it);
                                }
                            });

                            initInfo();
                        }
                    } catch (Exception ex) {
                        LogUtils.e(ex.getMessage() + "");
                    }
                }

                showContent();
            }
        });
    }

    private void requestDataById(final String id, final String type, final IReturnObject<IMCvnDBModel> returnObj) {
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("__session__", AppApplication.getSession());
        params.addQueryStringParameter("id", id);
        params.addQueryStringParameter("type", type);
        params.addQueryStringParameter("isFullMessage", "false");

        HttpSend(HttpMethod.POST, HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.GetConversationById),
                params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String result = responseInfo.result;
                        if (result != null) {
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                if (jsonObject.getBoolean("Succeed")) {

                                    JSONObject appJson = jsonObject.getJSONObject("Data").getJSONObject("Conversation");
                                    //
                                    String groupID = appJson.getString("groupID");
                                    String id = appJson.getString("id");
                                    String status = appJson.getString("status");
                                    String name = appJson.getString("name");
                                    String imgUrl = appJson.getString("imgUrl");
                                    String lastMessage = appJson.getString("lastMessage");
                                    String shortTime = appJson.getString("shortTime");
                                    String type = appJson.getString("type");
                                    int userCount = appJson.getInt("userCount");
                                    String partnerUser = appJson.getString("partnerUser");
                                    String draft = appJson.getString("draft");
                                    int unreadCount = appJson.getInt("unreadCount");
                                    String messagesInWnd = appJson.getString("messagesInWnd");
                                    String scrollOffsetOfWnd = appJson.getString("scrollOffsetOfWnd");
                                    //
                                    IMCvnDBModel model = new IMCvnDBModel();
                                    model.groupID = groupID;
                                    model.id = id;
                                    model.status = status;
                                    model.name = name;
                                    model.imgUrl = imgUrl;
                                    model.lastMessage = lastMessage;
                                    model.shortTime = shortTime;
                                    model.type = type;
                                    model.userCount = userCount;
                                    model.partnerUser = partnerUser;
                                    model.draft = draft;
                                    model.unreadCount = unreadCount;
                                    model.messagesInWnd = messagesInWnd;
                                    model.scrollOffsetOfWnd = scrollOffsetOfWnd;
                                    model.CurrUserID = AppApplication.getUser().EmplID;
                                    model.CurrWebSite = HttpUrlConstant.getWebSiteFullUrl("");

                                    returnObj.returnResult(model);
                                }
                            } catch (Exception e) {
                                LogUtils.e(e.getMessage() + "");
                            }
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                    }
                });

    }

    private void initInfo() {

        //手机
        if (!Check.isEmpty(mobile_info)) {

            View view = getLayoutInflater().inflate(R.layout.contact_info_item, null);
            LinearLayout materialRippleLayout = (LinearLayout) view.findViewById(R.id.ripp_item);
            LinearLayout divider = (LinearLayout) view.findViewById(R.id.linearLayoutDivider);
            TextView textViewTitle = (TextView) view.findViewById(R.id.textViewTitle);
            TextView textViewName = (TextView) view.findViewById(R.id.textViewName);
            textViewTitle.setText("手机");
            textViewName.setText(mobile_info);

            materialRippleLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Utils.requestCall(ContactInfo.this,mobile_info);
//                    final android.app.Dialog dialog = showSimpleCustomDialogMessage(R.layout.contact_info_dialog,true);
//                    if(dialog!=null){
//                        Button buttonCallPhone =(Button)dialog.findViewById(R.id.buttonCallPhone);
//                        buttonCallPhone.setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                PhoneUtil.callPhone(ContactInfo.this, mobile_info);
//                                dialog.dismiss();
//                            }
//                        });
//
//                        Button buttonCallSms =(Button)dialog.findViewById(R.id.buttonCallSms);
//                        buttonCallSms.setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                PhoneUtil.callSMS(ContactInfo.this, mobile_info, "");
//                                dialog.dismiss();
//                            }
//                        });
//
//                        Button buttonCancel =(Button)dialog.findViewById(R.id.buttonCancel);
//                        buttonCancel.setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                dialog.dismiss();
//                            }
//                        });
//                    }


                }
            });
            linearLayoutPhoneAndEmailInfo.addView(view);
        }

        //电话
        if (!Check.isEmpty(phone_info)) {
            String[] arrStr = phone_info.split(" ");
            final String phone = arrStr[arrStr.length - 1];
//            for(int i=0;i<arrStr.length;i++){
//                if(Check.isEmpty(arrStr[i])){
//                    continue;
//                }
            View view = getLayoutInflater().inflate(R.layout.contact_info_item, null);
            LinearLayout materialRippleLayout = (LinearLayout) view.findViewById(R.id.ripp_item);
            LinearLayout divider = (LinearLayout) view.findViewById(R.id.linearLayoutDivider);
            TextView textViewTitle = (TextView) view.findViewById(R.id.textViewTitle);
            TextView textViewName = (TextView) view.findViewById(R.id.textViewName);
            textViewTitle.setText("电话");
            textViewName.setText(phone_info);

//                if(i==arrStr.length-1 && Check.isEmpty(email_info)){
//                    divider.setVisibility(View.GONE);
//                }

//                final String phone_f = arrStr[i];
            materialRippleLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Utils.requestCall(ContactInfo.this,phone_info);
                }
            });
            linearLayoutPhoneAndEmailInfo.addView(view);
//            }
        }
        if (!Check.isEmpty(email_info)) {

            String[] arrStr = email_info.split(" ");
            for (int i = 0; i < arrStr.length; i++) {
                View view = getLayoutInflater().inflate(R.layout.contact_info_item, null);
                LinearLayout materialRippleLayout = (LinearLayout) view.findViewById(R.id.ripp_item);
                LinearLayout divider = (LinearLayout) view.findViewById(R.id.linearLayoutDivider);
                TextView textViewTitle = (TextView) view.findViewById(R.id.textViewTitle);
                TextView textViewName = (TextView) view.findViewById(R.id.textViewName);
                textViewTitle.setText("邮箱");
                textViewName.setText(arrStr[i]);

                if (i == arrStr.length - 1) {
                    divider.setVisibility(View.GONE);
                }

                final String email_f = arrStr[i];
                materialRippleLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showSimpleDialogMessage("是否发送邮件", new IReturnObject() {
                            @Override
                            public void returnResult(Object result) {
                                PhoneUtil.callEmail(ContactInfo.this, email_f);
                            }
                        }, true, true);

                    }
                });
                linearLayoutPhoneAndEmailInfo.addView(view);
            }

        }
        if (other_info_map.size() > 0) {
            linearLayoutOtherInfo.setVisibility(View.VISIBLE);
            for (String key : other_info_map.keySet()) {
                String other_info = other_info_map.get(key);

                String[] arrStr = other_info.split(" ");
                for (int i = 0; i < arrStr.length; i++) {
                    View view = getLayoutInflater().inflate(R.layout.contact_info_item, null);
                    LinearLayout materialRippleLayout = (LinearLayout) view.findViewById(R.id.ripp_item);
                    LinearLayout divider = (LinearLayout) view.findViewById(R.id.linearLayoutDivider);
                    TextView textViewTitle = (TextView) view.findViewById(R.id.textViewTitle);
                    TextView textViewName = (TextView) view.findViewById(R.id.textViewName);
                    ImageView imageView = (ImageView) view.findViewById(R.id.imageViewBtn);

                    textViewTitle.setText(key);
                    textViewName.setText(arrStr[i]);
                    imageView.setVisibility(View.INVISIBLE);
//                    materialRippleLayout.setDefaultRippleAlpha(0);

                    if (i == arrStr.length - 1) {
                        divider.setVisibility(View.GONE);
                    }

                    linearLayoutOtherInfo.addView(view);
                }

            }
        } else {
            linearLayoutOtherInfo.setVisibility(View.GONE);
        }
    }


}
